<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-monthName>
                <el-input
                  v-model="formInfo.data.monthName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  :placeholder="'请选择会计期间'"
                  style="width: 100%"
                >
                  <template #append>
                    <el-icon @click="checkFiscalPeriodStart()"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addRow>
                <el-button :disabled="!formInfo.data.monthName" @click="addRow"
                  >新增行</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                  >删除行</el-button
                >
              </template>
              <template v-slot:filter-addOtherMonth>
                <el-button
                  :disabled="!formInfo.data.monthName"
                  @click="addOtherMonth"
                  >参考其他会计期间添加</el-button
                >
              </template>
              <template v-slot:filter-addAll>
                <el-button :disabled="!formInfo.data.monthName" @click="addAll"
                  >添加全部方案</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <page-table
                  ref="table"
                  :class="{
                    isShow:
                      selectProductInfo.popoVisible ||
                      selectBatchInfo.popoVisible,
                  }"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tabIndex="false"
                  :check-box="true"
                  rowKey="tableIndex"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-planNo="scope">
                    <el-input
                      v-if="
                        scope.row.emptyRowType && scope.row.emptyRowType === '1'
                      "
                      :ref="'productRef' + scope.$index"
                      :class="'productKey' + scope.$index"
                      class="productKey"
                      :disabled="!formInfo.data.monthName"
                      placeholder="编码\名称"
                      v-model="scope.row.productKeyword"
                      @keyup.enter="planSearchInput(scope.row, scope.$index)"
                    >
                      <template #append>
                        <div
                          class="el-input-search"
                          @click="planSearch(scope.row, scope.$index)"
                        >
                          <el-icon style="vertical-align: middle">
                            <Search />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                    <span v-else>{{ scope.row.planNo }}</span>
                  </template>
                  <template v-slot:col-productCode="scope">
                    <el-input
                      v-if="
                        scope.row.emptyRowType &&
                        (scope.row.emptyRowType === '1' ||
                          scope.row.emptyRowType === '2')
                      "
                      :ref="'batchRef' + scope.$index"
                      :class="'batchKey' + scope.$index"
                      :disabled="!scope.row.analysisPlanId"
                      class="batchKey"
                      placeholder="编码\名称\规格\厂家"
                      v-model="scope.row.batchKeyword"
                      @keyup.enter="batchSearchInput(scope.row, scope.$index)"
                    >
                      <template #append>
                        <div
                          class="el-input-search"
                          @click="batchSearch(scope.row, scope.$index)"
                        >
                          <el-icon style="vertical-align: middle">
                            <Search />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                    <span v-else> {{ scope.row.productCode || '-' }} </span>
                  </template>
                  <template v-slot:col-proportion="scope">
                    <el-form-item
                      class="margin-bottom"
                      v-if="scope.row.productId"
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.proportion`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: validatorProportion,
                                        rowData: scope.row,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%"
                                v-model.lazy="scope.row.proportion"
                                clearable
                                controls-position="right"
                                :precision="2"
                                @change="changeLarge($event)"
                                :min="0.01"
                                :max="100"
                              />
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <SelectProduct
      v-if="selectProductInfo.visible"
      v-model:showDialog="selectProductInfo.visible"
      :query="selectProductInfo.query"
      :api="selectProductInfo.api"
      :highlightRow="false"
      :checkBox="true"
      title="可选方案"
      placeholder="编码\名称"
      @callback="selectProductBackList"
    />
    <SelectBatch
      v-if="selectBatchInfo.visible"
      v-model:showDialog="selectBatchInfo.visible"
      :popoVisible="selectBatchInfo.visible"
      :query="selectBatchInfo.query"
      :api="selectBatchInfo.api"
      :fieldList="selectBatchInfo.fieldList"
      :highlightRow="true"
      :checkBox="false"
      title="可选药品"
      placeholder="编码\名称\规格\厂家"
      @callback="selectBatchBack"
    ></SelectBatch>
    <el-popover
      v-if="selectProductInfo.popoVisible"
      ref="productPopoverRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      :virtual-ref="productRef"
      width="1000px"
      :visible="selectProductInfo.popoVisible"
      virtual-triggering
      @hide="productPopoHide"
    >
      <ProductTable
        v-if="selectProductInfo.popoVisible"
        :popoVisible="selectProductInfo.popoVisible"
        :query="selectProductInfo.query"
        :highlightRow="selectProductInfo.highlightRow"
        :checkBox="selectProductInfo.checkBox"
        :refresh="selectProductInfo.refresh"
        :api="selectProductInfo.api"
        :fieldList="selectProductInfo.fieldList"
        @checkMore="checkMore('product')"
        @reset="selectProductInfo.popoVisible = false"
        @callback="selectProductBack"
        @keyDown="productKeyDown"
      ></ProductTable>
    </el-popover>
    <el-popover
      v-if="selectBatchInfo.popoVisible"
      ref="batchPopoverRef"
      :virtual-ref="batchRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      width="1000px"
      :visible="selectBatchInfo.popoVisible"
      virtual-triggering
      @hide="batchPopoHide"
    >
      <ProductTable
        v-if="selectBatchInfo.popoVisible"
        :popoVisible="selectBatchInfo.popoVisible"
        :query="selectBatchInfo.query"
        :highlightRow="selectBatchInfo.highlightRow"
        :checkBox="selectBatchInfo.checkBox"
        :refresh="selectBatchInfo.refresh"
        :fieldList="selectBatchInfo.fieldList"
        :api="selectBatchInfo.api"
        @checkMore="checkMore('batch')"
        @reset="selectBatchInfo.popoVisible = false"
        @callback="selectBatchBack"
        @keyDown="batchKeyDown"
      ></ProductTable>
    </el-popover>
    <Proportion
      v-if="proportionInfo.visible"
      v-model:showDialog="proportionInfo.visible"
      :tableData="proportionInfo.tableData"
      :infoList="proportionInfo.infoList"
      title="药品占比详情"
      baseTitle="药品详情"
      @callback="proportionBack"
    />
    <SelectMonth
      v-if="selectMonthInfo.visible"
      v-model:showDialog="selectMonthInfo.visible"
      :options="selectMonthInfo.options"
      title="选择会计期间"
      @callback="selectMonthCallback"
    />
    <SelectFiscalPeriod
      v-if="selectFiscalPeriodInfo.visible"
      v-model:show-dialog="selectFiscalPeriodInfo.visible"
      :api="getBaseFiscalPeriodPage"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      :query="selectFiscalPeriodInfo.query"
      @callback="callBackSelectFiscalPeriod"
    />
  </div>
</template>

<script setup name="assetConsumablesModify">
import SelectProduct from '../components/SelectProduct'
import SelectBatch from '../components/SelectBatch'
import ProductTable from '../components/ProductTable'
import Proportion from '../components/proportion'
import SelectMonth from '../components/SelectMonth'
import {
  createAnalyMedicineCostBatchInsertByMonth,
  getAnalysisPlanPage,
  getAnalyMaterialMedicineCostMonthName,
  getAnalyMaterialMedicineCostAll,
  getAnalysisPlanAll,
} from '@/api/asset'
import { getProductPage } from '@/api/core.js'
import { getBaseFiscalPeriodPage } from '@/api/base'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
import _ from 'lodash'
import { setVal, setTabindex } from '@/common/js/base'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  orderId: {
    type: [Number, String],
  },
})
const validatorProportion = (rule, value, callback) => {
  if (!value) {
    return callback('请输入用量占用比例')
  } else {
    callback()
  }
}
//表单相关
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '会计期间',
      value: 'monthName',
      type: 'slot',
    },
    {
      label: '自动继承到下个会计期间',
      value: 'isInheritNextMonth',
      type: 'radio-model',
      code: 'default_yes_or_no',
    },
  ],
  rules: {
    monthName: [
      { required: true, message: '请选择会计期间', trigger: 'change' },
    ],
  },
  labelWidth: '160px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {},
  list: [
    { type: 'slot', value: 'addRow' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'addOtherMonth' },
    { type: 'slot', value: 'addAll' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  productSysGroup: [],
  data: [
    {
      emptyRowType: '1', //1添加产品和批次，2添加批次
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  fieldList: [
    {
      label: '分析方案编码',
      value: 'planNo',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '分析方案名称',
      value: 'planName',
      width: '100px',
    },
    {
      label: '分析部门',
      value: 'deptName',
    },
    {
      label: '分析类型',
      value: 'analysisTypeValue',
      width: '80px',
    },
    {
      label: '药品编码',
      align: 'left',
      value: 'productCode',
      type: 'slot',
      minWidth: '150px',
    },
    {
      label: '药品名称',
      value: 'commonName',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '厂家',
      value: 'brandName',
    },

    {
      label: '单价',
      value: 'price',
      type: 'column',
      // formatter: proxy.$fn.TripartiteMethod,
      width: '60px',
    },
    {
      label: '计量单位',
      value: 'unitName',
    },
    {
      label: '用量占用比例%',
      value: 'proportion',
      type: 'slot',
      width: '160px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '占比详情',
        event: proportionDetail,
        show: true,
        ifRender: function (row) {
          return row.productId
        },
      },
      {
        label: '删除行',
        event: removeBatch,
        show: true,
        ifRender: function (row) {
          return row.productId
        },
      },
      {
        label: '复制行',
        event: copyRow,
        show: true,
        ifRender: function (row) {
          return (row.emptyRowType && row.emptyRowType === '2') || row.productId
        },
      },
      {
        label: '新增行',
        event: addRow,
        show: true,
      },
    ],
  },
  bigWidth: {
    planNo: '100px',
    planName: '100px',
    deptName: '80px',
    analysisType: '80px',
    productCode: '100px',
    commonName: '100px',
    standard: '100px',
    brandName: '80px',
    price: '80px',
    unitName: '60px',
    proportion: '140px',
  },
  smallWidth: {
    planNo: '90px',
    planName: '90px',
    deptName: '60px',
    analysisType: '40px',
    productCode: '90px',
    commonName: '90px',
    standard: '100px',
    brandName: '80px',
    price: '50px',
    unitName: '50px',
    proportion: '90px',
  },
})

const selectProductInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    keyword: '',
  },
  api: getAnalysisPlanPage,
  highlightRow: true,
  checkBox: false,
  fieldList: [
    {
      label: '分析方案编码',
      value: 'planNo',
    },
    {
      label: '分析方案名称',
      value: 'planName',
    },
    {
      label: '分析部门',
      value: 'deptName',
    },
    {
      label: '分析类型',
      value: 'analysisTypeValue',
    },
  ],
})
const selectBatchInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    type: 4,
    status: 1,
    putShelfStatus: 1,
    keyword: '',
    idNotIn: '',
  },
  api: getProductPage,
  highlightRow: true,
  checkBox: false,
  fieldList: [
    {
      label: '药品编码',
      value: 'productCode',
    },
    {
      label: '药品名称',
      value: 'commonName',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '厂家',
      value: 'brandName',
      minWidth: '80px',
    },

    {
      label: '单价',
      value: 'price',
      type: 'column',
      // formatter: proxy.$fn.TripartiteMethod,
      minWidth: '60px',
    },
    {
      label: '单位',
      value: 'unitName',
      minWidth: '60px',
    },
  ],
})
const proportionInfo = ref({
  visible: false,
  tableData: [],
  data: [],
  infoList: {
    data: {},
    fieldList: [
      { label: '药品编码', value: 'productCode', type: 'text' },
      { label: '药品名称', value: 'commonName', type: 'text' },
      { label: '规格', value: 'standard', type: 'text' },
      { label: '厂家', value: 'brandName', type: 'text' },
      { label: '单价', value: 'price', type: 'text' },
      { label: '单位', value: 'unitName', type: 'text' },
    ],
  },
})
const selectFiscalPeriodInfo = ref({
  visible: false,
  query: {
    fiscalType: 2,
  },
})
const selectMonthInfo = ref({
  visible: false,
  options: [],
})
const productPopoverRef = ref()
const productRef = ref()
const batchPopoverRef = ref()
const batchRef = ref()
const formRefs = ref([])
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})

const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      let list = []
      tableInfo.value.data.forEach((item, index) => {
        if (item.emptyRowType && item.emptyRowType === '1') {
          let arr = [
            { key: 'productKey' + index, index: index },
            { key: 'batchKey' + index, index: index },
          ]
          list = list.concat(arr)
        } else if (item.emptyRowType && item.emptyRowType === '2') {
          list.push({ key: 'batchKey' + index, index: index })
        }
        item.tableIndex = index + 1
      })
      tableInfo.value.tabList = list
      setTabindex(proxy)
    }
  },
  { deep: true }
)

watch(
  () => selectBatchInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectProductInfo.value.popoVisible = false
    }
  }
)
watch(
  () => selectProductInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectBatchInfo.value.popoVisible = false
    }
  }
)

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)

window.addEventListener('click', closePopper, { passive: true })
window.addEventListener('keydown', addTab, true)
onActivated(() => {
  window.addEventListener('click', closePopper, { passive: true })
  window.addEventListener('keydown', addTab, true)
})
onDeactivated(() => {
  window.removeEventListener('click', closePopper, true)
  window.removeEventListener('keydown', addTab, true)
})
function addTab(val) {
  if (val.key === 'Tab') {
  }
}
function closePopper(e) {
  if (
    e.target.closest('.el-popper') ||
    e.target.closest('.productKey') ||
    e.target.closest('.batchKey')
  ) {
    // 点击当前元素处理操作
  } else {
    //点击非当前元素，需要执行的代码
    selectBatchInfo.value.popoVisible = false
    selectProductInfo.value.popoVisible = false
  }
}
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$fn.setFieldListColWidth(
    tableInfo.value.fieldList,
    tableInfo.value.bigWidth,
    tableInfo.value.smallWidth
  )
})
function checkFiscalPeriodStart() {
  selectFiscalPeriodInfo.value.visible = true
}
function callBackSelectFiscalPeriod(data) {
  if (data && data.id) {
    formInfo.data.monthName = data.name
    getAnalyMaterialMedicineCostAll({
      monthName: formInfo.data.monthName,
      type: 4,
    }).then((res) => {
      if (res && res.success) {
        tableInfo.value.data = res.data
        tableInfo.value.data.push({
          emptyRowType: '1',
          productKeyword: '',
          batchKeyword: '',
          id: new Date().getTime() + (1 + Math.random()),
        })
      }
    })
  } else {
    formInfo.data.monthName = ''
    tableInfo.value.data = [
      {
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      },
    ]
  }
}
//其他月
function addOtherMonth() {
  getAnalyMaterialMedicineCostMonthName({ type: 4 }).then((res) => {
    if (res && res.success && res.data && res.data.length) {
      let data = res.data.filter((item) => item !== formInfo.data.monthName)
      selectMonthInfo.value.options = data || []
      selectMonthInfo.value.visible = true
    }
  })
}
function selectMonthCallback(monthName, callback) {
  getAnalyMaterialMedicineCostAll({ type: 4, monthName: monthName }).then(
    (res) => {
      if (res && res.success) {
        tableInfo.value.data = res.data
        tableInfo.value.data.push({
          emptyRowType: '1',
          productKeyword: '',
          batchKeyword: '',
          id: new Date().getTime() + (1 + Math.random()),
        })
        callback()
      }
    }
  )
}
//全部添加
function addAll() {
  getAnalysisPlanAll().then((res) => {
    if (res && res.success && res.data && res.data.length) {
      let list = tableInfo.value.data.filter((item) => item.analysisPlanId)
      if (list.length) {
        proxy
          .$confirm('添加全部方案将覆盖已编辑方案，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            tableInfo.value.data = res.data.map((row) => {
              return {
                planNo: row.planNo,
                planName: row.planName,
                analysisPlanId: row.id,
                deptName: row.deptName,
                deptId: row.deptId,
                analysisType: row.analysisType,
                analysisTypeValue: row.analysisTypeValue,
                emptyRowType: '2',
              }
            })
            tableInfo.value.data.push({
              emptyRowType: '1',
              productKeyword: '',
              batchKeyword: '',
              id: new Date().getTime() + (1 + Math.random()),
            })
          })
      } else {
        tableInfo.value.data = res.data.map((row) => {
          return {
            planNo: row.planNo,
            planName: row.planName,
            analysisPlanId: row.id,
            deptName: row.deptName,
            deptId: row.deptId,
            analysisType: row.analysisType,
            analysisTypeValue: row.analysisTypeValue,
            emptyRowType: '2',
          }
        })
        tableInfo.value.data.push({
          emptyRowType: '1',
          productKeyword: '',
          batchKeyword: '',
          id: new Date().getTime() + (1 + Math.random()),
        })
      }
    }
  })
}
//占比详情
function proportionDetail(row) {
  let list = tableInfo.value.data.filter(
    (item) => item.productId === row.productId
  )
  proportionInfo.value.data = list
  proportionInfo.value.tableData = proxy.$fn.deepClone(list)
  proportionInfo.value.infoList.data = proxy.$fn.deepClone(list[0])
  proportionInfo.value.visible = true
}
function proportionBack(data) {
  let list = proportionInfo.value.data
  if (data && data.length) {
    let arr = []
    let planIds = data.map((item) => item.analysisPlanId)
    list.forEach((item) => {
      if (!planIds.includes(item.analysisPlanId)) {
        arr.push(item)
      }
    })
    if (arr && arr.length) {
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => !arr.includes(item)
      )
    }
    tableInfo.value.data.forEach((item, index) => {
      let itemKey = item.analysisPlanId + '&' + item.productId
      data.forEach((el) => {
        let elKey = el.analysisPlanId + '&' + el.productId
        if (itemKey === elKey) {
          tableInfo.value.data[index].proportion = el.proportion
        }
      })
    })
  } else {
    tableInfo.value.data = tableInfo.value.data.filter(
      (item) => !list.includes(item)
    )
  }
}
//复制行
function copyRow(row, index) {
  let obj = {
    planNo: row.planNo,
    planName: row.planName,
    analysisPlanId: row.analysisPlanId,
    deptName: row.deptName,
    deptId: row.deptId,
    analysisType: row.analysisType,
    analysisTypeValue: row.analysisTypeValue,
    emptyRowType: '2',
  }
  tableInfo.value.data.splice(index + 1, 0, obj)
}
//新增行
function addRow(row, index = '') {
  console.log(index)
  let obj = {
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  }
  if (index || index === 0) {
    tableInfo.value.data.splice(index + 1, 0, obj)
  } else {
    tableInfo.value.data.push(obj)
  }
}
function checkMore(str) {
  if (str === 'product') {
    let row = selectProductInfo.value.row
    let index = selectProductInfo.value.index
    planSearch(row, index)
  } else if (str === 'batch') {
    let row = selectBatchInfo.value.row
    let index = selectBatchInfo.value.index
    batchSearch(row, index)
  }
}
function planSearch(row, index) {
  //方案点击查询图标
  if (!formInfo.data.monthName) return
  selectProductInfo.value.query.keyword = row.productKeyword
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  selectProductInfo.value.visible = true
  selectProductInfo.value.popoVisible = false
}

function planSearchInput(row, index) {
  //方案enter查询
  if (!formInfo.data.monthName) return
  productRef.value = proxy.$refs['productRef' + index]
  selectProductInfo.value.query.keyword = row.productKeyword
  selectProductInfo.value.refresh = Math.random()
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  selectProductInfo.value.popoVisible = true
}
function productKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'productKey' + selectProductInfo.value.index
      setVal(className)
      selectProductInfo.value.popoVisible = false
      return
    }
    let className = 'productKey' + selectProductInfo.value.index
    let productKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    productKeyDom.blur()
  })
}
function selectProductBack(obj) {
  let index = selectProductInfo.value.index
  tableInfo.value.data[index] = {
    planNo: obj.planNo,
    planName: obj.planName,
    analysisPlanId: obj.id,
    deptName: obj.deptName,
    deptId: obj.deptId,
    analysisType: obj.analysisType,
    analysisTypeValue: obj.analysisTypeValue,
    emptyRowType: '2',
  }
  let itemList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  )
  if (!itemList.length) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function selectProductBackList(data) {
  let index = selectProductInfo.value.index
  let newData = data.map((item) => {
    return {
      planNo: item.planNo,
      planName: item.planName,
      analysisPlanId: item.id,
      deptName: item.deptName,
      deptId: item.deptId,
      analysisType: item.analysisType,
      analysisTypeValue: item.analysisTypeValue,
      emptyRowType: '2',
    }
  })
  let emptyRowTypeList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  ) //空行条数
  let list = proxy.$fn.deepClone(tableInfo.value.data)
  let leftList,
    rightList = []
  if (emptyRowTypeList.length > 1) {
    if (index === tableInfo.value.data.length - 1) {
      //是否最后一条
      leftList = list.slice(0, index)
      rightList = list.slice(index)
    } else {
      leftList = list.slice(0, index)
      rightList = list.slice(index + 1)
    }
  } else {
    leftList = list.slice(0, index)
    rightList = list.slice(index)
  }
  tableInfo.value.data = leftList.concat(newData).concat(rightList)
}
function productPopoHide() {
  selectProductInfo.value.popoVisible = false
}
function batchSearch(row, index) {
  //批次点击查询图标
  if (!row.analysisPlanId) return
  let productIds = tableInfo.value.data
    .filter(
      (item) => item.analysisPlanId === row.analysisPlanId && item.productId
    )
    .map((item) => item.productId)
  selectBatchInfo.value.query.idNotIn =
    productIds && productIds.length ? productIds.toString() : ''
  selectBatchInfo.value.query.keyword = row.batchKeyword
  selectBatchInfo.value.row = row
  selectBatchInfo.value.index = index
  selectBatchInfo.value.visible = true
  selectBatchInfo.value.popoVisible = false
}
function batchSearchInput(row, index) {
  //批次enter查询
  let timer = setTimeout(() => {
    if (!row.analysisPlanId) return
    let className = 'batchKey' + index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.focus()
    batchRef.value = proxy.$refs['batchRef' + index]
    let productIds = tableInfo.value.data
      .filter(
        (item) => item.analysisPlanId === row.analysisPlanId && item.productId
      )
      .map((item) => item.productId)
    selectBatchInfo.value.query.idNotIn =
      productIds && productIds.length ? productIds.toString() : ''
    selectBatchInfo.value.query.keyword = row.batchKeyword
    selectBatchInfo.value.refresh = Math.random()
    selectBatchInfo.value.row = row
    selectBatchInfo.value.index = index
    selectBatchInfo.value.popoVisible = true
    clearTimeout(timer)
  }, 0)
}
function batchPopoHide() {
  selectBatchInfo.value.popoVisible = false
}
function selectBatchBack(obj) {
  let index = selectBatchInfo.value.index
  let newObj = {
    commonName: obj.commonName,
    productCode: obj.productCode,
    standard: obj.standard,
    brandName: obj.brandName,
    price: obj.price || 0,
    unitName: obj.unitName,
    unitId: obj.unitId,
    proportion: obj.proportion || undefined,
    productId: obj.productId,
    emptyRowType: '',
  }
  tableInfo.value.data[index] = {
    ...tableInfo.value.data[index],
    ...newObj,
  }
}

function batchKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'batchKey' + selectProductInfo.value.index
      setVal(className)
      selectBatchInfo.value.popoVisible = false
      return
    }
    let className = 'batchKey' + selectBatchInfo.value.index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.blur()
  })
}

function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}

function changeLarge(e) {
  tableInfo.value.data.forEach((item, index) => {
    proxy.$refs.tableForm.clearValidate(`data.${index}.proportion`)
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function removeProduct() {
  tableInfo.value.data = tableInfo.value.data.filter(
    (item) => !tableInfo.value.selections.includes(item)
  )
  if (!tableInfo.value.data.length) {
    tableInfo.value.data = [
      {
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      },
    ]
  } else {
    let index = tableInfo.value.data.findIndex(
      (item) => item.emptyRowType === '1'
    )
    if (index === -1) {
      tableInfo.value.data.push({
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      })
    }
  }
}
//删除行右侧
function removeBatch(row, index) {
  tableInfo.value.data[index] = {
    planNo: row.planNo,
    planName: row.planName,
    analysisPlanId: row.analysisPlanId,
    deptName: row.deptName,
    deptId: row.deptId,
    analysisType: row.analysisType,
    analysisTypeValue: row.analysisTypeValue,
    emptyRowType: '2',
  }
}

// 触发事件
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let list = tableInfo.value.data.filter(
      (item) => item.analysisPlanId && item.productId && item.proportion > 0
    )
    if (!list.length) {
      proxy.$message({
        message: `请添加有效明细信息`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let groupData = _.groupBy(list, 'productId')
    let groupArr = Object.values(groupData)
    let arr = []
    groupArr.forEach((item) => {
      let proportion = 0
      item.forEach((el) => {
        proportion = proxy.$fn.accAdd(el.proportion || 0, proportion)
      })
      if (proportion > 100) {
        arr.push(`产品：${item[0].commonName}，编码：${item[0].productCode}`)
      }
    })
    if (arr.length) {
      proxy.$message({
        message: `【${arr}】的用量占用比例之和大于100%，请修改`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    list.forEach((item) => {
      item.monthName = formInfo.data.monthName
      item.isInheritNextMonth = formInfo.data.isInheritNextMonth
      item.type = 4
    })
    createAnalyMedicineCostBatchInsertByMonth(list).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
</script>

<style scoped lang="scss">
.el-input-search {
  width: 100%;
  height: 100%;
}
</style>
